package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageBean;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;

    @Override
    public PageBean list(Integer page, Integer pageSize) {
        // 1.调用Mapper层接口获取总记录数
        Integer count = empMapper.getCount();

        // 2.调用Mapper层接口获取当前页面的数据
        Integer startIndex = (page - 1) * pageSize;
        List<Emp> list = empMapper.list(startIndex, pageSize);

        return new PageBean(count, list);
    }

    @Override
    public PageBean page(String name, Integer gender, LocalDate begin, LocalDate end, Integer page, Integer pageSize) {
        // 1.开启分页查询
        PageHelper.startPage(page, pageSize);

        // 2.执行正常的查询所有记录
        List<Emp> emps = empMapper.page(name, gender, begin, end);

        // 3.将结果的List集合强制成Page对象
        Page<Emp> empPage = (Page<Emp>) emps;
        return new PageBean((int) empPage.getTotal(), empPage.getResult());
    }

    @Override
    public void delete(List<Integer> ids) {
        empMapper.delete(ids);
    }

    @Override
    public void save(Emp emp) {
        // 补充实体类基础属性
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());

        // 调用Mapper层接口保存数据
        empMapper.save(emp);
    }

    @Override
    public Emp getById(Integer id) {
        Emp emp = empMapper.getById(id);
        return emp;
    }

    @Override
    public void update(Emp emp) {
        // 1.补充基础属性
        emp.setUpdateTime(LocalDateTime.now());

        // 2.调用Mapper接口更新数据
        empMapper.update(emp);

    }

    @Override
    public Emp getByUsernameAndPassword(Emp emp) {
        return empMapper.getByUsernameAndPassword(emp);
    }
}
